package com.orangelife.utils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

/**
 * 金额工具类
 * 
 * @author GERRARD
 */
public final class MoneyUtil {
	
	public static void main(String[] args) {

		String amount = "99999.99";
		System.out.println(MoneyUtil.transferMoneyToWord(amount));

		System.out.println("小写金额" + amount + "转换大写金额:" + toChinese("99999.99"));

		String chnAmount = "玖萬玖仟玖佰玖拾玖圓玖角玖分";

		System.out.println(chnAmount + "-简体化:" + toSimplified(chnAmount));

		System.out.println("小写金额：" + amount + " 与 大写金额:" + chnAmount
				+ "比较结果--------" + isAmtEqChn(amount, chnAmount));
		 int val = 0; 
	        long s = System.nanoTime(); 
	        val = cnNumericToArabic("三亿二千零六万七千五百六", true); 
	        System.out.println(val); 
	        val = cnNumericToArabic("一九九八", true); 
	        System.out.println(val); 
	        long e = System.nanoTime(); 
	        System.out.format("Done[" + val + "], cost: %.5fsec\n", 
	                ((float) (e - s)) / 1E9); 
	}
	// 默认除法运算精度
	private static final int DEF_DIV_SCALE = 10;
	/**
	 * 大写数字
	 */
	private static final String[] NUMBERS = { "零", "壹", "贰", "叁", "肆", "伍",
			"陆", "柒", "捌", "玖" };

	/**
	 * 整数单位
	 */
	private static final String[] IUNIT = { "元", "拾", "佰", "仟", "万", "拾", "佰",
			"仟", "亿", "拾", "佰", "仟", "万", "拾", "佰", "仟" };

	/**
	 * 小数单位
	 */
	private static final String[] DUNIT = { "角", "分", "厘" };
	/***
	 * 个位英文
	 */

	private static String[] smallNumbers = new String[] { "ZERO", "ONE", "TWO",
			"THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN",
			"ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN",
			"SEVENTEEN", "EIGHTEEN", "NINETEEN" };
	/**
	 * 十位數英文
	 */
	private static String[] tensNumbers = new String[] { "", "", "TWENTY",
			"THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY" };
	/**
	 * 千百万 英文
	 */
	private static String[] scaleNumers = new String[] { "", "THOUSAND",
			"MILLION", "BILLION" };
	 private static final Character[] CN_NUMERIC = { '一', '二', '三', '四', '五', 
         '六', '七', '八', '九', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖', 
         '十', '百', '千', '拾', '佰', '仟', '万', '亿', '○', 'Ｏ', '零' }; 

 private static Map<Character, Integer> cnNumeric = null; 

 static { 
     cnNumeric = new HashMap<Character, Integer>(40, 0.85f); 
     for (int j = 0; j < 9; j++) 
         cnNumeric.put(CN_NUMERIC[j], j + 1); 
     for (int j = 9; j < 18; j++) 
         cnNumeric.put(CN_NUMERIC[j], j - 8); 
     cnNumeric.put('两', 2); 
     cnNumeric.put('十', 10); 
     cnNumeric.put('拾', 10); 
     cnNumeric.put('百', 100); 
     cnNumeric.put('佰', 100); 
     cnNumeric.put('千', 1000); 
     cnNumeric.put('仟', 1000); 
     cnNumeric.put('万', 10000); 
     cnNumeric.put('亿', 100000000); 
 }

	/**
	 * 大写金额
	 * 
	 * @param str
	 * @return
	 */
	public static String toChinese(String str) {
		str = str.replaceAll(",", "");// 去掉","

		String integerStr;// 整数部分数字

		String decimalStr;// 小数部分数字

		// 初始化：分离整数部分和小数部分
		if (str.indexOf(".") > 0) {
			integerStr = str.substring(0, str.indexOf("."));

			decimalStr = str.substring(str.indexOf(".") + 1);

		} else if (str.indexOf(".") == 0) {
			integerStr = "";
			decimalStr = str.substring(1);

		} else {
			integerStr = str;
			decimalStr = "";
		}

		// integerStr去掉首0，不必去掉decimalStr的尾0(超出部分舍去)
		if (!integerStr.equals("")) {
			integerStr = Long.toString(Long.parseLong(integerStr));

			if (integerStr.equals("0")) {
				integerStr = "";
			}
		}

		// overflow超出处理能力，直接返回
		if (integerStr.length() > IUNIT.length) {
			System.out.println(str + ":超出处理能力");
			return str;
		}

		int[] integers = toArray(integerStr);// 整数部分数字

		boolean isMust5 = isMust5(integerStr);// 设置万单位

		int[] decimals = toArray(decimalStr);// 小数部分数字

		return getChineseInteger(integers, isMust5)
				+ getChineseDecimal(decimals);
	}

	/**
	 * 整数部分和小数部分转换为数组，从高位至低位
	 * 
	 * @param number
	 * @return
	 */
	private static int[] toArray(String number) {
		int[] array = new int[number.length()];

		for (int i = 0; i < number.length(); i++) {
			array[i] = Integer.parseInt(number.substring(i, i + 1));
		}
		return array;
	}

	/**
	 * 中文整数金额
	 * 
	 * @param integers
	 * @param isMust5
	 * @return
	 */
	private static String getChineseInteger(int[] integers, boolean isMust5) {
		StringBuffer chineseInteger = new StringBuffer("");

		int length = integers.length;

		for (int i = 0; i < length; i++) {
			// 0出现在关键位置：1234(万)5678(亿)9012(万)3456(元)
			// 特殊情况：10(拾元、壹拾元、壹拾万元、拾万元)
			String key = "";

			if (integers[i] == 0) {
				if ((length - i) == 13)// 万(亿)(必填)
				{
					key = IUNIT[4];
				}

				else if ((length - i) == 9)// 亿(必填)
				{
					key = IUNIT[8];
				}

				else if ((length - i) == 5 && isMust5)// 万(不必填)
				{
					key = IUNIT[4];
				}

				else if ((length - i) == 1)// 元(必填)
				{
					key = IUNIT[0];
				}

				// 0遇非0时补零，不包含最后一位
				if ((length - i) > 1 && integers[i + 1] != 0) {
					key += NUMBERS[0];
				}

			}
			chineseInteger.append(integers[i] == 0 ? key
					: (NUMBERS[integers[i]] + IUNIT[length - i - 1]));
		}
		return chineseInteger.toString();
	}

	/**
	 * 中文小数金额
	 * 
	 * @param decimals
	 * @return
	 */
	private static String getChineseDecimal(int[] decimals) {
		StringBuffer chineseDecimal = new StringBuffer("");

		for (int i = 0; i < decimals.length; i++) {
			// 舍去3位小数之后的
			if (i == 3)
				break;

			chineseDecimal.append(decimals[i] == 0 ? ""
					: (NUMBERS[decimals[i]] + DUNIT[i]));
		}
		return chineseDecimal.toString();
	}

	/**
	 * 第五位数字是否加万
	 * 
	 * @param integerStr
	 * @return
	 */
	private static boolean isMust5(String integerStr) {
		int length = integerStr.length();

		if (length > 4) {
			String subInteger = "";

			if (length > 8) {
				// 取得从低位数，第5到第8位的字串
				subInteger = integerStr.substring(length - 8, length - 4);
			} else {
				subInteger = integerStr.substring(0, length - 4);
			}
			return Integer.parseInt(subInteger) > 0;
		} else {
			return false;
		}
	}

	/**
	 * 大小写金额比较 支持最小单位：厘
	 * 
	 * @param amount
	 *            小写金额
	 * @param chineseAmount
	 *            大写金额
	 * @return
	 */
	public static boolean isAmtEqChn(String amount, String chineseAmount) {

		if (StringUtils.isBlank(chineseAmount)) {
			return false;
		}

		// 格式化大写金额去整
		chineseAmount = chineseAmount.replace("整", "");
		chineseAmount = chineseAmount.replace("正", "");
		chineseAmount = chineseAmount.replace("人民币", "");

		chineseAmount = toSimplified(chineseAmount);

		String toChnAmt = toChinese(amount);

		if (chineseAmount.equals(toChnAmt)) {
			return true;
		}
		return false;
	}

	/**
	 * 大写金额简体化
	 * 
	 * @param chnAmt
	 * @return
	 */
	public static String toSimplified(String chnAmt) {

		if (StringUtils.isBlank(chnAmt)) {
			return null;
		}

		char[] amtArrChar = chnAmt.toCharArray();

		Map<String, String> mapping = getSimpToTradMapping();

		for (int i = 0; i < amtArrChar.length; i++) {
			if (mapping.containsKey(String.valueOf(amtArrChar[i]))) {
				amtArrChar[i] = mapping.get(String.valueOf(amtArrChar[i]))
						.charAt(0);
			}
		}

		return String.valueOf(amtArrChar);
	}

	/**
	 * 繁体对应
	 * 
	 * @return
	 */
	private static Map<String, String> getSimpToTradMapping() {

		Map<String, String> mapping = new HashMap<String, String>();

		mapping.put("圆", "元");
		mapping.put("圓", "元");
		mapping.put("貳", "贰");
		mapping.put("陸", "陆");
		mapping.put("億", "亿");
		mapping.put("萬", "万");

		return mapping;
	}

	

	/**
	 * 提供精确的加法运算。
	 * 
	 * @param v1
	 *            被加数
	 * @param v2
	 *            加数
	 * @return 两个参数的和
	 */

	public static double add(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.add(b2).doubleValue();
	}

	/**
	 * 提供精确的减法运算。
	 * 
	 * @param v1
	 *            被减数
	 * @param v2
	 *            减数
	 * @return 两个参数的差
	 */

	public static double sub(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.subtract(b2).doubleValue();
	}

	/**
	 * 提供精确的乘法运算。
	 * 
	 * @param v1
	 *            被乘数
	 * @param v2
	 *            乘数
	 * @return 两个参数的积
	 */

	public static double mul(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.multiply(b2).doubleValue();
	}

	/**
	 * 提供（相对）精确的除法运算，当发生除不尽的情况时，精确到 小数点以后10位，以后的数字四舍五入。
	 * 
	 * @param v1
	 *            被除数
	 * @param v2
	 *            除数 www.2cto.com
	 * @return 两个参数的商
	 */

	public static double div(double v1, double v2) {
		return div(v1, v2, DEF_DIV_SCALE);
	}

	/**
	 * 提供（相对）精确的除法运算。当发生除不尽的情况时，由scale参数指 定精度，以后的数字四舍五入。
	 * 
	 * @param v1
	 *            被除数
	 * @param v2
	 *            除数
	 * @param scale
	 *            表示表示需要精确到小数点以后几位。
	 * @return 两个参数的商
	 */

	public static double div(double v1, double v2, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException(
					"The   scale   must   be   a   positive   integer   or   zero");
		}
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	/**
	 * 提供精确的小数位四舍五入处理。
	 * 
	 * @param v
	 *            需要四舍五入的数字
	 * @param scale
	 *            小数点后保留几位
	 * @return 四舍五入后的结果
	 */

	public static double round(double v, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException(
					"The   scale   must   be   a   positive   integer   or   zero");
		}
		BigDecimal b = new BigDecimal(Double.toString(v));
		BigDecimal one = new BigDecimal("1");
		return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	/**
	 * // 四舍五入保留一位;
	 * 
	 * @param a
	 * @return
	 */

	public static double randomMath(double a) {
		BigDecimal b = new BigDecimal(a);
		// 四舍五入保留二位;
		BigDecimal c = b.setScale(1, BigDecimal.ROUND_HALF_UP);
		a = c.doubleValue();
		return a;
	}

	/**
	 * // 四舍五入保留二位;
	 * 
	 * @param a
	 * @return
	 */
	public static float randomMath(float a) {
		BigDecimal b = new BigDecimal(a);
		// 四舍五入保留二位;
		BigDecimal c = b.setScale(2, BigDecimal.ROUND_HALF_UP);
		a = c.floatValue();
		return a;
	}

	public static String transferMoneyToWord(String money) {
		double dMoney = Double.parseDouble(money);
		String[] arrMoney = money.split("\\.");
		// 小数点前
		int decimals1 = 0;
		// 小数点后
		int decimals2 = 0;
		// 纯小数
		if (dMoney < 1) {
			decimals1 = 0;
		} else {
			decimals1 = Integer.parseInt(arrMoney[0]);
		}
		decimals2 = arrMoney.length > 1 ? Integer.parseInt(arrMoney[1]) : 0;
		// 初始化显示英文为ZERO
		String combined1 = smallNumbers[0];
		String combined2 = smallNumbers[0];

		if (decimals1 != 0) {
			int[] digitGroups = new int[] { 0, 0, 0, 0 };
			// //将金额拆分成4段，每段放3位数，即：XXX,XXX,XXX,XXX。最大仅支持到Billion，
			for (int i = 0; i < 4; i++) {
				digitGroups[i] = decimals1 % 1000;
				decimals1 = decimals1 / 1000;
			}

			String[] groupText = new String[] { "", "", "", "" };
			// 处理每段的金额转英文，百位+十位+个位
			for (int i = 0; i < 4; i++) {
				int hundreds = digitGroups[i] / 100;
				int tensUnits = digitGroups[i] % 100;

				// 百位
				if (hundreds != 0) {
					groupText[i] = groupText[i] + smallNumbers[hundreds]
							+ " HUNDRED";
					if (tensUnits != 0) {
						groupText[i] = groupText[i] + " AND ";
					}
				}

				// 十位和个位
				int tens = tensUnits / 10;
				int units = tensUnits % 10;
				if (tens >= 2) {// 十位大于等于20
					groupText[i] = groupText[i] + tensNumbers[tens];
					if (units != 0) {
						groupText[i] = groupText[i] + " " + smallNumbers[units];
					}
				} else if (tens != 0) {// 十位和个位，小于20的情况
					groupText[i] = groupText[i] + smallNumbers[tensUnits];
				} else if (units != 0) {
					groupText[i] = groupText[i] + smallNumbers[units];
				}
			}
			// 金额的个十百位赋值到combined
			combined1 = groupText[0];
			// 将金额排除个十百位以外，余下的3段英文数字，加上千位分隔符英文单词，Thousand/Million/Billion
			for (int i = 1; i < 4; i++) {
				if (digitGroups[i] != 0) {
					String prefix = groupText[i] + " " + scaleNumers[i]; // A:组合Thousand
																			// 和Billion
					if (combined1.length() != 0) { // 如果金额的百位+十位+个位非0,则在后面加上空格
						prefix = prefix + " ";
					}
					combined1 = prefix + combined1; // 再连接 A+B

				}
			}
		}

		if (decimals2 != 0) {
			// 十位和个位
			int tens = decimals2 / 10;
			int units = decimals2 % 10;

			if (decimals2 >= 20) {
				combined2 = "CENTS " + tensNumbers[tens];
				if (units != 0) {
					combined2 = combined2 + " " + smallNumbers[units];
				}
			} else if (decimals2 > 1) {// 19到2之间
				combined2 = "CENTS " + smallNumbers[decimals2];
			} else {
				combined2 = "CENT " + smallNumbers[decimals2];
			}
		}

		if (!combined1.equals("ZERO")) {
			if (!combined2.equals("ZERO")) {
				return (combined1 + " " + combined2).toLowerCase();
			} else {
				return combined1.toLowerCase();
			}
		} else if (!combined2.equals("ZERO")) {
			return combined2.toLowerCase();
		} else {
			return "ZERO".toLowerCase();
		}
	}
	     public static int isCNNumeric(char c) { 
      Integer i = cnNumeric.get(c); 
      if (i == null) 
          return -1; 
      return i.intValue(); 
  } 
  public static int cnNumericToArabic(String cnn, boolean flag) { 
 
      cnn = cnn.trim(); 
      if (cnn.length() == 1) 
          return isCNNumeric(cnn.charAt(0)); 
 
      if (flag) 
          cnn = cnn.replace('佰', '百').replace('仟', '千').replace('拾', '十') 
                  .replace('零', ' '); 
      // System.out.println(cnn); 
      int yi = -1, wan = -1, qian = -1, bai = -1, shi = -1; 
      int val = 0; 
      yi = cnn.lastIndexOf('亿'); 
      if (yi > -1) { 
          val += cnNumericToArabic(cnn.substring(0, yi), false) * 100000000; 
          if (yi < cnn.length() - 1) 
              cnn = cnn.substring(yi + 1, cnn.length()); 
          else 
              cnn = ""; 
 
          if (cnn.length() == 1) { 
              int arbic = isCNNumeric(cnn.charAt(0)); 
              if (arbic <= 10) 
                  val += arbic * 10000000; 
              cnn = ""; 
          } 
      } 
 
      wan = cnn.lastIndexOf('万'); 
      if (wan > -1) { 
          val += cnNumericToArabic(cnn.substring(0, wan), false) * 10000; 
          if (wan < cnn.length() - 1) 
              cnn = cnn.substring(wan + 1, cnn.length()); 
          else 
              cnn = ""; 
          if (cnn.length() == 1) { 
              int arbic = isCNNumeric(cnn.charAt(0)); 
              if (arbic <= 10) 
                  val += arbic * 1000; 
              cnn = ""; 
          } 
      } 
 
      qian = cnn.lastIndexOf('千'); 
      if (qian > -1) { 
          val += cnNumericToArabic(cnn.substring(0, qian), false) * 1000; 
          if (qian < cnn.length() - 1) 
              cnn = cnn.substring(qian + 1, cnn.length()); 
          else 
              cnn = ""; 
          if (cnn.length() == 1) { 
              int arbic = isCNNumeric(cnn.charAt(0)); 
              if (arbic <= 10) 
                  val += arbic * 100; 
              cnn = ""; 
          } 
      } 
 
      bai = cnn.lastIndexOf('百'); 
      if (bai > -1) { 
          val += cnNumericToArabic(cnn.substring(0, bai), false) * 100; 
          if (bai < cnn.length() - 1) 
              cnn = cnn.substring(bai + 1, cnn.length()); 
          else 
              cnn = ""; 
          if (cnn.length() == 1) { 
              int arbic = isCNNumeric(cnn.charAt(0)); 
              if (arbic <= 10) 
                  val += arbic * 10; 
              cnn = ""; 
          } 
      } 
 
      shi = cnn.lastIndexOf('十'); 
      if (shi > -1) { 
          if (shi == 0) 
              val += 1 * 10; 
          else 
              val += cnNumericToArabic(cnn.substring(0, shi), false) * 10; 
          if (shi < cnn.length() - 1) 
              cnn = cnn.substring(shi + 1, cnn.length()); 
          else 
              cnn = ""; 
      } 
 
      cnn = cnn.trim(); 
      for (int j = 0; j < cnn.length(); j++) 
          val += isCNNumeric(cnn.charAt(j)) 
                  * Math.pow(10, cnn.length() - j - 1); 
 
      return val; 
  } 
 
  public static int qCNNumericToArabic(String cnn) { 
      int val = 0; 
      cnn = cnn.trim(); 
      for (int j = 0; j < cnn.length(); j++) 
          val += isCNNumeric(cnn.charAt(j)) 
                  * Math.pow(10, cnn.length() - j - 1); 
      return val; 
  } 
	
}
